<?php

declare(strict_types=1);

namespace App\Rpc\Consumer;

use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Arr;
use Hyperf\Utils\Str;
use App\Auth\Guard\AdminJwtGuard;
use App\Model\AdminUser;
use PhpAmqpLib\Message\AMQPMessage;
use Qbhy\HyperfAuth\AuthManager;
use Qbhy\HyperfAuth\Exception\UnauthorizedException;

/**
 * @Consumer(name="AuthConsumer", nums=2)
 */
class AuthConsumer extends ConsumerMessage
{
    public function __construct()
    {
        $this->exchange = env('APP_NAME');
        $this->routingKey = 'backend-rpc-auth';
        $this->queue = env('APP_NAME') . '-backend-rpc-auth';
    }

    /**
     * @param $data
     * @param AMQPMessage $message
     * @return string
     */
    public function consumeMessage($data, AMQPMessage $message): string
    {
        try {
            $token = $data['token'];
            if (Str::startsWith($token, 'Bearer ')) {
                 $token = Str::substr($token, 7);
            }
            $AuthManager = ApplicationContext::getContainer()->get(AuthManager::class);
            $AuthGuard = $AuthManager->guard('backend-api-jwt');
            /* @var AdminJwtGuard $AuthGuard */
            $AdminUser = $AuthGuard->user($token);
            if (!$AdminUser->user_status) {
                throw new UnauthorizedException("此账号已被禁用，请联系系统管理员", $AuthGuard);
            }
            /* @var AdminUser $AdminUser */
            $result_data = [
                'code' => 200,
                'message' => 'success',
                'data' => [
                    'admin_user' => Arr::only($AdminUser->toArray(), ['id', 'username', 'name']),
                ],
            ];
        } catch (\Throwable $e) {
            $result_data = [
                'code' => $e->getCode() ?: 500,
                'message' => $e->getMessage(),
                'data' => (object) [],
            ];
        }
        $this->reply($result_data, $message);
        return Result::ACK;
    }
}
